home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / etc / python2.4 / site.py
Encoding:
Python Source  |  2007-04-12  |  14.0 KB  |  420 lines

  1. """Append module search paths for third-party packages to sys.path.
  2.  
  3. ****************************************************************
  4. * This module is automatically imported during initialization. *
  5. ****************************************************************
  6.  
  7. In earlier versions of Python (up to 1.5a3), scripts or modules that
  8. needed to use site-specific modules would place ``import site''
  9. somewhere near the top of their code.  Because of the automatic
  10. import, this is no longer necessary (but code that does it still
  11. works).
  12.  
  13. This will append site-specific paths to the module search path.  On
  14. Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
  15. appends lib/python<version>/site-packages as well as lib/site-python.
  16. On other platforms (mainly Mac and Windows), it uses just sys.prefix
  17. (and sys.exec_prefix, if different, but this is unlikely).  The
  18. resulting directories, if they exist, are appended to sys.path, and
  19. also inspected for path configuration files.
  20.  
  21. FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
  22. Local addons go into /usr/local/lib/python<version>/site-packages
  23. (resp. /usr/local/lib/site-python), Debian addons install into
  24. /usr/{lib,share}/python<version>/site-packages.
  25.  
  26. A path configuration file is a file whose name has the form
  27. <package>.pth; its contents are additional directories (one per line)
  28. to be added to sys.path.  Non-existing directories (or
  29. non-directories) are never added to sys.path; no directory is added to
  30. sys.path more than once.  Blank lines and lines beginning with
  31. '#' are skipped. Lines starting with 'import' are executed.
  32.  
  33. For example, suppose sys.prefix and sys.exec_prefix are set to
  34. /usr/local and there is a directory /usr/local/lib/python2.3/site-packages
  35. with three subdirectories, foo, bar and spam, and two path
  36. configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
  37. following:
  38.  
  39.   # foo package configuration
  40.   foo
  41.   bar
  42.   bletch
  43.  
  44. and bar.pth contains:
  45.  
  46.   # bar package configuration
  47.   bar
  48.  
  49. Then the following directories are added to sys.path, in this order:
  50.  
  51.   /usr/local/lib/python2.3/site-packages/bar
  52.   /usr/local/lib/python2.3/site-packages/foo
  53.  
  54. Note that bletch is omitted because it doesn't exist; bar precedes foo
  55. because bar.pth comes alphabetically before foo.pth; and spam is
  56. omitted because it is not mentioned in either path configuration file.
  57.  
  58. After these path manipulations, an attempt is made to import a module
  59. named sitecustomize, which can perform arbitrary additional
  60. site-specific customizations.  If this import fails with an
  61. ImportError exception, it is silently ignored.
  62.  
  63. """
  64.  
  65. import sys
  66. import os
  67. import __builtin__
  68.  
  69.  
  70. def makepath(*paths):
  71.     dir = os.path.abspath(os.path.join(*paths))
  72.     return dir, os.path.normcase(dir)
  73.  
  74. def abs__file__():
  75.     """Set all module' __file__ attribute to an absolute path"""
  76.     for m in sys.modules.values():
  77.         try:
  78.             m.__file__ = os.path.abspath(m.__file__)
  79.         except AttributeError:
  80.             continue
  81.  
  82. def removeduppaths():
  83.     """ Remove duplicate entries from sys.path along with making them
  84.     absolute"""
  85.     # This ensures that the initial path provided by the interpreter contains
  86.     # only absolute pathnames, even if we're running from the build directory.
  87.     L = []
  88.     known_paths = set()
  89.     for dir in sys.path:
  90.         # Filter out duplicate paths (on case-insensitive file systems also
  91.         # if they only differ in case); turn relative paths into absolute
  92.         # paths.
  93.         dir, dircase = makepath(dir)
  94.         if not dircase in known_paths:
  95.             L.append(dir)
  96.             known_paths.add(dircase)
  97.     sys.path[:] = L
  98.     return known_paths
  99.  
  100. # XXX This should not be part of site.py, since it is needed even when
  101. # using the -S option for Python.  See http://www.python.org/sf/586680
  102. def addbuilddir():
  103.     """Append ./build/lib.<platform> in case we're running in the build dir
  104.     (especially for Guido :-)"""
  105.     from distutils.util import get_platform
  106.     s = "build/lib%s.%s-%.3s" % (sys.pydebug and '_d' or '', get_platform(), sys.version)
  107.     s = os.path.join(os.path.dirname(sys.path[-1]), s)
  108.     sys.path.append(s)
  109.  
  110. def _init_pathinfo():
  111.     """Return a set containing all existing directory entries from sys.path"""
  112.     d = set()
  113.     for dir in sys.path:
  114.         try:
  115.             if os.path.isdir(dir):
  116.                 dir, dircase = makepath(dir)
  117.                 d.add(dircase)
  118.         except TypeError:
  119.             continue
  120.     return d
  121.  
  122. def addpackage(sitedir, name, known_paths):
  123.     """Add a new path to known_paths by combining sitedir and 'name' or execute
  124.     sitedir if it starts with 'import'"""
  125.     if known_paths is None:
  126.         _init_pathinfo()
  127.         reset = 1
  128.     else:
  129.         reset = 0
  130.     fullname = os.path.join(sitedir, name)
  131.     try:
  132.         f = open(fullname, "rU")
  133.     except IOError:
  134.         return
  135.     try:
  136.         for line in f:
  137.             if line.startswith("#"):
  138.                 continue
  139.             if line.startswith("import"):
  140.                 exec line
  141.                 continue
  142.             line = line.rstrip()
  143.             dir, dircase = makepath(sitedir, line)
  144.             if not dircase in known_paths and os.path.exists(dir):
  145.                 sys.path.append(dir)
  146.                 known_paths.add(dircase)
  147.     finally:
  148.         f.close()
  149.     if reset:
  150.         known_paths = None
  151.     return known_paths
  152.  
  153. def addsitedir(sitedir, known_paths=None):
  154.     """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  155.     'sitedir'"""
  156.     if known_paths is None:
  157.         known_paths = _init_pathinfo()
  158.         reset = 1
  159.     else:
  160.         reset = 0
  161.     sitedir, sitedircase = makepath(sitedir)
  162.     if not sitedircase in known_paths:
  163.         sys.path.append(sitedir)        # Add path component
  164.     try:
  165.         names = os.listdir(sitedir)
  166.     except os.error:
  167.         return
  168.     names.sort()
  169.     for name in names:
  170.         if name.endswith(os.extsep + "pth"):
  171.             addpackage(sitedir, name, known_paths)
  172.     if reset:
  173.         known_paths = None
  174.     return known_paths
  175.  
  176. def addsitepackages(known_paths):
  177.     """Add site-packages (and possibly site-python) to sys.path"""
  178.     prefixes = [os.path.join(sys.prefix, "local"), sys.prefix]
  179.     if sys.exec_prefix != sys.prefix:
  180.         prefixes.append(os.path.join(sys.exec_prefix, "local"))
  181.     for prefix in prefixes:
  182.         if prefix:
  183.             if sys.platform in ('os2emx', 'riscos'):
  184.                 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
  185.             elif os.sep == '/':
  186.                 sitedirs = [os.path.join(prefix,
  187.                                          "lib",
  188.                                          "python" + sys.version[:3],
  189.                                          "site-packages"),
  190.                             os.path.join(prefix, "lib", "site-python")]
  191.             else:
  192.                 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
  193.             if sys.platform == 'darwin':
  194.                 # for framework builds *only* we add the standard Apple
  195.                 # locations. Currently only per-user, but /Library and
  196.                 # /Network/Library could be added too
  197.                 if 'Python.framework' in prefix:
  198.                     home = os.environ.get('HOME')
  199.                     if home:
  200.                         sitedirs.append(
  201.                             os.path.join(home,
  202.                                          'Library',
  203.                                          'Python',
  204.                                          sys.version[:3],
  205.                                          'site-packages'))
  206.             for sitedir in sitedirs:
  207.                 if os.path.isdir(sitedir):
  208.                     addsitedir(sitedir, known_paths)
  209.     return None
  210.  
  211.  
  212. def setBEGINLIBPATH():
  213.     """The OS/2 EMX port has optional extension modules that do double duty
  214.     as DLLs (and must use the .DLL file extension) for other extensions.
  215.     The library search path needs to be amended so these will be found
  216.     during module import.  Use BEGINLIBPATH so that these are at the start
  217.     of the library search path.
  218.  
  219.     """
  220.     dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
  221.     libpath = os.environ['BEGINLIBPATH'].split(';')
  222.     if libpath[-1]:
  223.         libpath.append(dllpath)
  224.     else:
  225.         libpath[-1] = dllpath
  226.     os.environ['BEGINLIBPATH'] = ';'.join(libpath)
  227.  
  228.  
  229. def setquit():
  230.     """Define new built-ins 'quit' and 'exit'.
  231.     These are simply strings that display a hint on how to exit.
  232.  
  233.     """
  234.     if os.sep == ':':
  235.         exit = 'Use Cmd-Q to quit.'
  236.     elif os.sep == '\\':
  237.         exit = 'Use Ctrl-Z plus Return to exit.'
  238.     else:
  239.         exit = 'Use Ctrl-D (i.e. EOF) to exit.'
  240.     __builtin__.quit = __builtin__.exit = exit
  241.  
  242.  
  243. class _Printer(object):
  244.     """interactive prompt objects for printing the license text, a list of
  245.     contributors and the copyright notice."""
  246.  
  247.     MAXLINES = 23
  248.  
  249.     def __init__(self, name, data, files=(), dirs=()):
  250.         self.__name = name
  251.         self.__data = data
  252.         self.__files = files
  253.         self.__dirs = dirs
  254.         self.__lines = None
  255.  
  256.     def __setup(self):
  257.         if self.__lines:
  258.             return
  259.         data = None
  260.         for dir in self.__dirs:
  261.             for filename in self.__files:
  262.                 filename = os.path.join(dir, filename)
  263.                 try:
  264.                     fp = file(filename, "rU")
  265.                     data = fp.read()
  266.                     fp.close()
  267.                     break
  268.                 except IOError:
  269.                     pass
  270.             if data:
  271.                 break
  272.         if not data:
  273.             data = self.__data
  274.         self.__lines = data.split('\n')
  275.         self.__linecnt = len(self.__lines)
  276.  
  277.     def __repr__(self):
  278.         self.__setup()
  279.         if len(self.__lines) <= self.MAXLINES:
  280.             return "\n".join(self.__lines)
  281.         else:
  282.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  283.  
  284.     def __call__(self):
  285.         self.__setup()
  286.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  287.         lineno = 0
  288.         while 1:
  289.             try:
  290.                 for i in range(lineno, lineno + self.MAXLINES):
  291.                     print self.__lines[i]
  292.             except IndexError:
  293.                 break
  294.             else:
  295.                 lineno += self.MAXLINES
  296.                 key = None
  297.                 while key is None:
  298.                     key = raw_input(prompt)
  299.                     if key not in ('', 'q'):
  300.                         key = None
  301.                 if key == 'q':
  302.                     break
  303.  
  304. def setcopyright():
  305.     """Set 'copyright' and 'credits' in __builtin__"""
  306.     __builtin__.copyright = _Printer("copyright", sys.copyright)
  307.     if sys.platform[:4] == 'java':
  308.         __builtin__.credits = _Printer(
  309.             "credits",
  310.             "Jython is maintained by the Jython developers (www.jython.org).")
  311.     else:
  312.         __builtin__.credits = _Printer("credits", """\
  313.     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  314.     for supporting Python development.  See www.python.org for more information.""")
  315.     here = os.path.dirname(os.__file__)
  316.     __builtin__.license = _Printer(
  317.         "license", "See http://www.python.org/%.3s/license.html" % sys.version,
  318.         ["LICENSE.txt", "LICENSE"],
  319.         [os.path.join(here, os.pardir), here, os.curdir])
  320.  
  321.  
  322. class _Helper(object):
  323.     """Define the built-in 'help'.
  324.     This is a wrapper around pydoc.help (with a twist).
  325.  
  326.     """
  327.  
  328.     def __repr__(self):
  329.         return "Type help() for interactive help, " \
  330.                "or help(object) for help about object."
  331.     def __call__(self, *args, **kwds):
  332.         import pydoc
  333.         return pydoc.help(*args, **kwds)
  334.  
  335. def sethelper():
  336.     __builtin__.help = _Helper()
  337.  
  338. def aliasmbcs():
  339.     """On Windows, some default encodings are not provided by Python,
  340.     while they are always available as "mbcs" in each locale. Make
  341.     them usable by aliasing to "mbcs" in such a case."""
  342.     if sys.platform == 'win32':
  343.         import locale, codecs
  344.         enc = locale.getdefaultlocale()[1]
  345.         if enc.startswith('cp'):            # "cp***" ?
  346.             try:
  347.                 codecs.lookup(enc)
  348.             except LookupError:
  349.                 import encodings
  350.                 encodings._cache[enc] = encodings._unknown
  351.                 encodings.aliases.aliases[enc] = 'mbcs'
  352.  
  353. def setencoding():
  354.     """Set the string encoding used by the Unicode implementation.  The
  355.     default is 'ascii', but if you're willing to experiment, you can
  356.     change this."""
  357.     encoding = "ascii" # Default value set by _PyUnicode_Init()
  358.     if 0:
  359.         # Enable to support locale aware default string encodings.
  360.         import locale
  361.         loc = locale.getdefaultlocale()
  362.         if loc[1]:
  363.             encoding = loc[1]
  364.     if 0:
  365.         # Enable to switch off string to Unicode coercion and implicit
  366.         # Unicode to string conversion.
  367.         encoding = "undefined"
  368.     if encoding != "ascii":
  369.         # On Non-Unicode builds this will raise an AttributeError...
  370.         sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  371.  
  372.  
  373. def execsitecustomize():
  374.     """Run custom site specific code, if available."""
  375.     try:
  376.         import sitecustomize
  377.     except ImportError:
  378.         pass
  379.  
  380.  
  381. def main():
  382.     abs__file__()
  383.     paths_in_sys = removeduppaths()
  384.     if (os.name == "posix" and sys.path and
  385.         os.path.basename(sys.path[-1]) == "Modules"):
  386.         addbuilddir()
  387.     paths_in_sys = addsitepackages(paths_in_sys)
  388.     if sys.platform == 'os2emx':
  389.         setBEGINLIBPATH()
  390.     setquit()
  391.     setcopyright()
  392.     sethelper()
  393.     aliasmbcs()
  394.     setencoding()
  395.     execsitecustomize()
  396.     # Remove sys.setdefaultencoding() so that users cannot change the
  397.     # encoding after initialization.  The test for presence is needed when
  398.     # this module is run as a script, because this code is executed twice.
  399.     if hasattr(sys, "setdefaultencoding"):
  400.         del sys.setdefaultencoding
  401.     # install the apport exception handler if available
  402.     try:
  403.         import apport_python_hook
  404.     except ImportError:
  405.         pass
  406.     else:
  407.         apport_python_hook.install()
  408.  
  409.  
  410. main()
  411.  
  412. def _test():
  413.     print "sys.path = ["
  414.     for dir in sys.path:
  415.         print "    %r," % (dir,)
  416.     print "]"
  417.  
  418. if __name__ == '__main__':
  419.     _test()
  420.